<template>
  <div ref="chart" class="chart"></div>
</template>

<script>
import { markRaw } from "vue";
import * as echarts from "echarts";
import { debounce } from "@/utils";
export default {
  props: {
    option: {
      type: Object,
      default: () => {},
      require: true,
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  watch: {
    option: {
      handler() {
        this.renderChart();
      },
      deep: true,
      immediate: true,
    },
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.func);
    this.chart && this.chart.dispose();
    this.chart = null;
  },
  mounted() {
    this.func = debounce(() => {
      this.resize();
    }, 300);
    this.initChart();
    window.addEventListener("resize", this.func);
  },
  methods: {
    initChart() {
      this.chart = markRaw(echarts.init(this.$refs["chart"]));
      this.renderChart();
    },
    renderChart() {
      if (this.chart && Object.keys(this.option).length) {
        // console.log("option_1", this.option);
        this.chart.setOption(this.option, true);
      }
    },
    resize() {
      // console.log("option_2", this.option);
      this.chart && this.chart.resize();
    },
  },
};
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>
